package com.yzs.exam.service.Impl;

import com.yzs.exam.config.property.SystemConfig;
import com.yzs.exam.entity.User;
import com.yzs.exam.service.AuthenticationService;
import com.yzs.exam.service.UserService;
import com.yzs.exam.utils.RsaUtil;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * @author yzs
 * @create 2021-03-19 10:46
 */
@Service
@AllArgsConstructor
public class AuthenticationServiceImpl implements AuthenticationService{


    private final UserService userService;
    private final SystemConfig systemConfig;


    @Override
    public boolean authUser(String username, String password) {
        User user = userService.getUserByUserName(username);
        return authUser(user,username,password);
    }

    @Override
    public boolean authUser(User user, String username, String password) {
        if(user == null){
            return false;
        }
        String encodePwd = user.getPassword();
        if (null == encodePwd || encodePwd.length() == 0) {
            return false;
        }
        String pwd = pwdDecode(encodePwd);
        return pwd.equals(password);
    }

    /**
     * 密码加密
     * @param password password
     * @return
     */
    @Override
    public String pwdEncode(String password) {
        return RsaUtil.rsaEncode(systemConfig.getPwdKey().getPublicKey(), password);
    }

    /**
     * 密码解密
     * @param encodePwd
     * @return
     */
    @Override
    public String pwdDecode(String encodePwd) {
        return RsaUtil.rsaDecode(systemConfig.getPwdKey().getPrivateKey(), encodePwd);
    }
}
